package chen.web.back.client.system;

import chen.web.back.client.FormDataBuilder;
import chen.web.back.client.UrlHelper;

import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Status;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Element;

public class SiteForm  extends LayoutContainer  {

	@Override
	protected void onRender(Element parent, int index) {
		// TODO Auto-generated method stub
		super.onRender(parent, index);
		VerticalPanel vp = new VerticalPanel();
		vp.add(createForm());
		add(vp);
		loadData();
	}
	
	private TextField<String> siteName = null;
	private TextArea description = null;
	private TextField<String> baseURL = null;
	private TextField<String> adminEmail = null;
	private Button saveButton = null;
	private Button reset = null;
	private Status status = null;
	private SiteConfig config = null;
	private FormPanel createForm() {
		FormPanel simple = new FormPanel();
		simple.setHeading("站点设置");
		simple.setFrame(true);
		simple.setWidth(420);
		simple.setFieldWidth(300);
		
		siteName = new TextField<String>();
		siteName.setFieldLabel("网站名称");
		siteName.setAllowBlank(false);
		siteName.getFocusSupport().setPreviousId(simple.getButtonBar().getId());
		simple.add(siteName);
		
		description = new TextArea(); 
		description.setFieldLabel("网站描述");
		description.setHeight(100);
		description.setAllowBlank(false);
		simple.add(description);
		
		baseURL = new TextField<String>();
		baseURL.setFieldLabel("网站根目录");
		baseURL.setAllowBlank(false);
		simple.add(baseURL);	

		adminEmail = new TextField<String>();
		adminEmail.setFieldLabel("管理员邮箱");
		adminEmail.setAllowBlank(false);
		simple.add(adminEmail);
		
		status = new Status();
		status.setBusy("please wait...");
		status.hide();
		status.setAutoWidth(true);
		simple.getButtonBar().add(status);
		
		saveButton = new Button("保存");
		saveButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
			public void componentSelected(ButtonEvent ce) {
				saveData();
			}
		});
		saveButton.disable();
		simple.addButton(saveButton);
		
		reset = new Button("重置");
		reset.addSelectionListener(new SelectionListener<ButtonEvent>() {
			public void componentSelected(ButtonEvent ce) {
				loadData();
			}
		});
		reset.disable();
		simple.addButton(reset);
		
		
		Listener<BaseEvent> inputListener = new Listener<BaseEvent>(){
			@Override
			public void handleEvent(BaseEvent be) {
				// TODO Auto-generated method stub
				if(!siteName.getValue().equals(config.getSiteName()) ||
						!description.getValue().equals(config.getDescription())	||
						!baseURL.getValue().equals(config.getBaseURL()) ||
						!adminEmail.getValue().equals(config.getAdminEmail())			
				){
					saveButton.enable();
					reset.enable();
				}
			}
			
		};
		
		siteName.addListener(Events.OnChange, inputListener);
		description.addListener(Events.OnChange, inputListener);
		baseURL.addListener(Events.OnChange, inputListener);
		adminEmail.addListener(Events.OnChange, inputListener);
		
		siteName.addListener(Events.OnKeyPress, inputListener);
		description.addListener(Events.OnKeyPress, inputListener);
		baseURL.addListener(Events.OnKeyPress, inputListener);
		adminEmail.addListener(Events.OnKeyPress, inputListener);
		
		return simple;
	}
	
	private void saveData(){
		status.show();
		saveButton.disable();
		reset.disable();
		RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, UrlHelper.toAbsolute("/config/site"));
		builder.setHeader("Content-Type", "application/json; charset=UTF-8");
		try {
			FormDataBuilder fdb = new FormDataBuilder();
			fdb.addProperty("siteName", siteName.getValue())
				.addProperty("baseURL", baseURL.getValue())
				.addProperty("description", description.getValue())
				.addProperty("adminEmail", adminEmail.getValue());
			builder.sendRequest(fdb.toJSONString(), new RequestCallback(){

				@Override
				public void onError(Request arg0, Throwable arg1) {
					// TODO Auto-generated method stub
					displayError("Couldn't retrieve JSON");
				}

				@Override
				public void onResponseReceived(Request request, Response response) {
					// TODO Auto-generated method stub
					if (200 == response.getStatusCode()) {
						JSONValue json = JSONParser.parseStrict(response
								.getText());
						JSONValue processValue = json.isObject().get("success");
						if(processValue != null && processValue.isBoolean().booleanValue()){
							loadData();
						} else {
							displayError(response.getText());
						}
						status.hide();
					}  else {
						displayError("Couldn't retrieve JSON ("
								+ response.getStatusText() + ")");
					}
				}
				
			});
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			displayError("Couldn't retrieve JSON");
		}
	}
	
	private void loadData(){
		status.show();
		saveButton.disable();
		reset.disable();
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, UrlHelper.toAbsolute("/config/site"));
		try {
			builder.sendRequest(null, new RequestCallback(){

				@Override
				public void onError(Request arg0, Throwable arg1) {
					// TODO Auto-generated method stub
					displayError("Couldn't retrieve JSON");
				}

				@Override
				public void onResponseReceived(Request request, Response response) {
					// TODO Auto-generated method stub
					if (200 == response.getStatusCode()) {
						JSONValue json = JSONParser.parseStrict(response
								.getText()).isObject().get("returnObject");

						String BaseURL = json.isObject().get("baseURL").isString().stringValue();
						String Description = json.isObject().get("description").isString().stringValue();
						String AdminEmail = json.isObject().get("adminEmail").isString().stringValue();
						String SiteName = json.isObject().get("siteName").isString().stringValue();
						config = new SiteConfig();
						config.setAdminEmail(AdminEmail);
						config.setBaseURL(BaseURL);
						config.setDescription(Description);
						config.setSiteName(SiteName);
						siteName.setValue(SiteName);
						description.setValue(Description);
						baseURL.setValue(BaseURL);
						adminEmail.setValue(AdminEmail);
						status.hide();
					}  else {
						displayError("Couldn't retrieve JSON ("
								+ response.getStatusText() + ")");
					}
				}
				
			});
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			displayError("Couldn't retrieve JSON");
		}
	}
	
	private static class SiteConfig{
		private String BaseURL;
		private String Description;
		private String AdminEmail;
		private String SiteName;
		
		public String getBaseURL() {
			return BaseURL;
		}
		public void setBaseURL(String baseURL) {
			BaseURL = baseURL;
		}
		public String getDescription() {
			return Description;
		}
		public void setDescription(String description) {
			Description = description;
		}
		public String getAdminEmail() {
			return AdminEmail;
		}
		public void setAdminEmail(String adminEmail) {
			AdminEmail = adminEmail;
		}
		public String getSiteName() {
			return SiteName;
		}
		public void setSiteName(String siteName) {
			SiteName = siteName;
		}
	}
	
	private void displayError(String message){
		status.hide();
		saveButton.enable();
		reset.enable();
		MessageBox.alert("出错", message, null);
	}
	
}
